package com.geek.factory.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.dto.OrderRequestDTO;
import com.geek.factory.entity.Orders;
import com.geek.factory.service.OrdersService;
import com.geek.factory.vo.OrderQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.geek.factory.result.Result;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-19
 */
@RestController
@RequestMapping("/orders")
@Api(tags = "后台系统的 - 合同模块 - 订单管理")
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @ApiOperation("通过ID查询订单信息")
    @GetMapping("{id}")
    public Result findOrderById(@ApiParam("订单ID") @PathVariable("id") Long id) {
        Orders role = ordersService.getById(id);
        log.info("order: {}", role);
        if(role!=null){
            return new Result(SuccessConstant.SUCCESS,"查询成功",role);
        }
        return new Result(SuccessConstant.FAIL,"查询失败");
    }

    @ApiOperation("通过订单类型查询订单信息")
    @GetMapping("type/{type}")
    public Result findOrderByType(@ApiParam("订单类型") @PathVariable("type") String type) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderType, type);
        Orders role = ordersService.getOne(wrapper);
        log.info("order: {}", role);
        if(role!=null){
            return new Result(SuccessConstant.SUCCESS,"查询成功",role);
        }
        return new Result(SuccessConstant.FAIL,"查询失败");
    }

@ApiOperation("新增订单")
@PostMapping("add")
public Result addOrder(@RequestBody OrderRequestDTO orderRequestDTO) {
    log.info("接收到的完整请求对象: {}", orderRequestDTO);
    
    // 检查请求对象是否为空
    if (orderRequestDTO == null) {
        log.error("请求对象为空，请检查请求体格式");
        return new Result(SuccessConstant.FAIL, "请求数据不能为空");
    }
    
    Orders orders = orderRequestDTO.getOrders();
    List<Integer> contractIds = orderRequestDTO.getContractIds();

    log.info("接收到的订单数据: {}", orders);
    log.info("接收到的合同ID: {}", contractIds);

    // 检查订单对象是否为空
    if (orders == null) {
        log.error("订单数据为空");
        return new Result(SuccessConstant.FAIL, "订单数据不能为空");
    }

    // 验证必填字段
    if (orders.getNumber() == null || orders.getOrderType() == null) {
        log.error("缺少必填字段: number={}, orderType={}", orders.getNumber(), orders.getOrderType());
        return new Result(SuccessConstant.FAIL, "缺少必填字段：订单号和订单类型");
    }

    Integer[] tContractIds = contractIds != null ? contractIds.toArray(new Integer[0]) : new Integer[0];
//    boolean save = ordersService.save(tContractIds, orders);
//    log.info("保存结果: {}", save);
//
//    if(save){
//        return new Result(SuccessConstant.SUCCESS, "新增成功");
//    }
//    return new Result(SuccessConstant.FAIL, "新增失败");
    try {
        boolean save = ordersService.save(tContractIds, orders);
        if(save){
            // 检查并记录未开票订单情况
            long uninvoicedCount = ordersService.count(
                    new LambdaQueryWrapper<Orders>()
                            .eq(Orders::getIsInvoiced, false));

            log.warn("新增订单后未开票订单数量: {}", uninvoicedCount);

            return new Result(SuccessConstant.SUCCESS, "新增成功");
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    } catch (Exception e) {
        log.error("新增订单失败", e);
        return new Result(SuccessConstant.FAIL, "新增失败: " + e.getMessage());
    }
}

    @ApiOperation("删除订单")
    @DeleteMapping("{id}")
    public Result deleteOrder(@ApiParam("用户ID") @PathVariable("id") Long id) {
        boolean delete = ordersService.removeById(id);
        log.info("delete: {}", delete);
        if(delete){
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }




    @ApiOperation("分页查询订单列表")
    @PostMapping("list")
    public Result findPage(
            @ApiParam("当前页码") @RequestParam(value = "now", required = false, defaultValue = "1") Integer now,
            @ApiParam("每页数量") @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
            @ApiParam("查询条件") @RequestBody(required = false) OrderQueryVO orderQueryVO
    ) {
        Page<Orders> page = new Page<>(now, size);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        if (orderQueryVO != null) {
            if (StringUtils.hasLength(orderQueryVO.getNumber())) {
                wrapper.like(Orders::getNumber, orderQueryVO.getNumber());
            }
            if (StringUtils.hasLength(orderQueryVO.getOrderType())) {
                wrapper.eq(Orders::getOrderType, orderQueryVO.getOrderType());
            }
            if (orderQueryVO.getMinAmount() != null) {
                wrapper.ge(Orders::getAmount, orderQueryVO.getMinAmount());
            }
            if (orderQueryVO.getMaxAmount() != null) {
                wrapper.le(Orders::getAmount, orderQueryVO.getMaxAmount());
            }
            if (orderQueryVO.getPayStatus() != null) {
                wrapper.eq(Orders::getPayStatus, orderQueryVO.getPayStatus());
            }
            if (orderQueryVO.getOrderStatus() != null) {
                wrapper.eq(Orders::getOrderStatus, orderQueryVO.getOrderStatus());
            }
            if (orderQueryVO.getIsInvoiced() != null) {
                wrapper.eq(Orders::getIsInvoiced, orderQueryVO.getIsInvoiced());
            }
        }
        // 关键：加上倒序排序
        wrapper.orderByDesc(Orders::getOrderDate); // 或 Orders::getCreatedTime

        Page<Orders> orderPage = ordersService.page(page, wrapper);

        // 修改返回逻辑，即使没有数据也返回成功
        return new Result(SuccessConstant.SUCCESS, "查询成功", orderPage);
    }


    @ApiOperation("查询订单关联的合同ID列表")
    @GetMapping("{orderId}/contracts")
    public Result findOrderContracts(@ApiParam("订单ID") @PathVariable("orderId") Long orderId) {
        try {
            List<Integer> contractIds = ordersService.findContractIdsByOrderId(orderId);
            log.info("订单 {} 关联的合同ID: {}", orderId, contractIds);
            return new Result(SuccessConstant.SUCCESS, "查询成功", contractIds);
        } catch (Exception e) {
            log.error("查询订单关联合同失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("修改订单及关联合同")
    @PutMapping()
    public Result updateOrder(@RequestBody OrderRequestDTO orderRequestDTO) {
        try {
            boolean update = ordersService.updateOrderWithContracts(
                    orderRequestDTO.getOrders(),
                    orderRequestDTO.getContractIds() != null ?
                            orderRequestDTO.getContractIds().toArray(new Integer[0]) :
                            new Integer[0]
            );
            log.info("update: {}", update);
            if(update){
                return new Result(SuccessConstant.SUCCESS, "修改成功");
            }
            return new Result(SuccessConstant.FAIL, "修改失败");
        } catch (Exception e) {
            log.error("修改订单失败", e);
            return new Result(SuccessConstant.FAIL, "修改失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取未开票订单数量")
    @GetMapping("uninvoiced/count")
    public Result getUninvoicedOrderCount() {
        try {
            LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Orders::getIsInvoiced, false); // 查询未开票的订单

            long count = ordersService.count(wrapper);
            log.info("未开票订单数量: {}", count);

            return new Result(SuccessConstant.SUCCESS, "查询成功", count);
        } catch (Exception e) {
            log.error("查询未开票订单数量失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取未开票订单列表（用于大屏显示）")
    @GetMapping("uninvoiced/list")
    public Result getUninvoicedOrders(
            @ApiParam("限制数量") @RequestParam(value = "limit", required = false, defaultValue = "5") Integer limit) {
        try {
            LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Orders::getIsInvoiced, false) // 查询未开票的订单
                    .orderByDesc(Orders::getOrderDate) // 按订单日期倒序
                    .last("LIMIT " + limit); // 限制返回数量

            List<Orders> orders = ordersService.list(wrapper);
            log.info("未开票订单列表: {}", orders.size());

            return new Result(SuccessConstant.SUCCESS, "查询成功", orders);
        } catch (Exception e) {
            log.error("查询未开票订单列表失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取大屏订单数据总览")
    @GetMapping("dashboard/overview")
    public Result getOrderDashboardOverview(
            @ApiParam("时间范围：day/week/month") @RequestParam(defaultValue = "day") String range) {
        try {
            Map<String, Object> result = new LinkedHashMap<>();

            // 1. 基本统计
            result.put("totalOrders", ordersService.count());
            result.put("statusDistribution", ordersService.getOrderStatusDistribution());

            // 2. 时间范围计算
            LocalDateTime end = LocalDateTime.now();
            LocalDateTime start = end.minusDays("day".equals(range) ? 1 : "week".equals(range) ? 7 : 30);

            // 3. 时间序列数据
            result.put("timeSeries", ordersService.getOrderTimeSeries(start, end,
                    "day".equals(range) ? "hour" : "day"));

            // 4. 金额统计
            result.put("amountStats", ordersService.getAmountStatistics());

            // 5. 金额趋势（按状态）
            result.put("amountTrend", ordersService.getAmountTrendByStatus(start, end));

            return new Result(SuccessConstant.SUCCESS, "查询成功", result);
        } catch (Exception e) {
            log.error("获取大屏数据失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }


    @ApiOperation("获取未开票订单提醒信息")
    @GetMapping("uninvoiced/reminders")
    public Result getUninvoicedOrderReminders() {
        try {
            Map<String, Object> reminders = ordersService.getUninvoicedOrderReminders();
            log.info("未开票订单提醒信息: {}", reminders);

            // 构建前端需要的提醒消息
            List<String> messages = new ArrayList<>();

            // 1. 总数提醒
            long count = (long) reminders.get("uninvoicedCount");
            if (count > 0) {
                messages.add(String.format("当前还有%d个订单未开票", count));
            }

            // 2. 最旧订单提醒
            Orders oldest = (Orders) reminders.get("oldestUninvoicedOrder");
            if (oldest != null) {
                messages.add(String.format("最久未开票订单: %s (创建于%s)",
                        oldest.getNumber(),
                        oldest.getOrderDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))));
            }

            // 3. 大额订单提醒
            @SuppressWarnings("unchecked")
            List<Orders> recentOrders = (List<Orders>) reminders.get("recentUninvoicedOrders");
            recentOrders.stream()
                    .filter(order -> order.getAmount().compareTo(new BigDecimal("10000")) > 0)
                    .forEach(order -> messages.add(String.format("大额未开票订单: %s (金额: %s)",
                            order.getNumber(),
                            order.getAmount())));

            return new Result(SuccessConstant.SUCCESS, "查询成功", messages);
        } catch (Exception e) {
            log.error("获取未开票订单提醒失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }





}
